/**
 * Created by FeLiX on 2016/9/18.
 */
const fs = require('fs');
const config = require('../config');

//添加路由
function addMapping(router, mapping) {
  for (var url in mapping) {
    if (url.startsWith('GET ')) {
      var path = url.substring(4);
      router.get(path, mapping[url]);
      console.log(`register URL mapping: GET ${path}`);
    } else if (url.startsWith('POST ')) {
      var path = url.substring(5);
      router.post(path, mapping[url]);
      console.log(`register URL mapping: POST ${path}`);
    } else {
      console.log(`invalid URl: ${url}`);
    }
  }
}

//加载控制器文件
function addControllers(router) {

  var files = fs.readdirSync(config.controllerDir);
  var js_files = files.filter((f)=> {
    return f.endsWith('.js');
  }, files);

  for (var f of js_files) {
    console.log(`process controller: ${f}...`);
    var mapping = require(config.controllerDir + f);
    addMapping(router, mapping);
  }
}

module.exports = addControllers;